package com.haixiaoke.saas.contract.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasc.open.api.bean.common.CorpIdentInfo;
import com.fasc.open.api.bean.common.UserIdentInfo;
import com.fasc.open.api.v5_1.res.corp.CorpIdentityInfoRes;
import com.fasc.open.api.v5_1.res.org.EmployeeInfo;
import com.fasc.open.api.v5_1.res.user.UserIdentityInfoRes;
import com.haixiaoke.saas.bill.service.IHouseBillService;
import com.haixiaoke.saas.bill.service.IProprietorBillService;
import com.haixiaoke.saas.common.constant.ContractConstants;
import com.haixiaoke.saas.common.constant.ProprietorConstants;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.enums.BillStateEnum;
import com.haixiaoke.saas.common.enums.ProprietorContractEnum;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.contract.domain.LesseeContract;
import com.haixiaoke.saas.contract.domain.Proprietor;
import com.haixiaoke.saas.contract.domain.ProprietorContract;
import com.haixiaoke.saas.contract.domain.ProxyService;
import com.haixiaoke.saas.contract.fadada.service.FaDaDaService;
import com.haixiaoke.saas.contract.service.ILesseeContractService;
import com.haixiaoke.saas.contract.service.IProprietorContractService;
import com.haixiaoke.saas.contract.service.IProprietorService;
import com.haixiaoke.saas.contract.service.IProxyServiceService;
import com.haixiaoke.saas.department.domain.ElectronicVisa;
import com.haixiaoke.saas.department.domain.ElectronicVisaSignProgress;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.IElectronicVisaService;
import com.haixiaoke.saas.department.service.IElectronicVisaSignProgressService;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.house.service.IHouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 法大大回调服务
 *
 * @author panda
 * @Date 2024/6/13
 **/
@Slf4j
@Service
public class FaDaDaCallbackService {

    @Autowired
    private IElectronicVisaService electronicVisaService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private ILesseeContractService lesseeContractService;
    @Autowired
    private IProprietorContractService proprietorContractService;
    @Autowired
    private IProprietorService proprietorService;
    @Autowired
    private IProxyServiceService proxyServiceService;
    @Autowired
    private IElectronicVisaSignProgressService electronicVisaSignProgressService;
    @Autowired
    private FaDaDaService faDaDaService;
    @Autowired
    private IHouseBillService houseBillService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IProprietorBillService propertiesBillService;

    /**
     * 处理回调
     *
     * @param event 事件id
     * @param map   <a href="https://dev.fadada.com/api-doc/HZRSAZQXZR/0T8MZCFRRZTU646K/5-1"/>
     */
    @Transactional
    public void disposeCallback(String event, Map<String, Object> map) {
        if (ObjectUtil.isNull(map)) {
            log.error("回调事件，map为空");
            return;
        }
        switch (event) {
            case "user-authorize":
                log.info("个人用户授权事件 data:{}", map);
                this.userAuth(map);
                break;
            case "corp-authorize":
                log.info("企业用户授权事件 data:{}", map);
                this.enterpriseAuth(map);
                break;
            case "sign-task-signed":
                log.info("签署任务参与方签署成功事件 data:{}", map);
                this.signed(map);
                break;
            case "sign-task-finished":
                log.info("签署任务完成事件 data:{}", map);
                this.finished(map);
                break;
            case "sign-task-sign-rejected":
                log.info("参与方拒签 data:{}", map);
                this.visaRejected(map);
                break;
            case "sign-task-canceled":
                log.info("签署任务撤销 data:{}", map);
                this.canceled(map);
                break;
            case "sign-task-expire":
                log.info("签署任务逾期 data:{}", map);
                this.expire(map);
                break;
        }

    }

    private void expire(Map<String, Object> map) {
        String signTaskId = map.get("signTaskId").toString();
        LesseeContract lesseeContract = lesseeContractService.selectLesseeContractByFlowId(signTaskId);
        ProprietorContract proprietorContract = proprietorContractService.selectProprietorContractByFlowId(signTaskId);
        if (ObjectUtil.isEmpty(lesseeContract) && ObjectUtil.isEmpty(proprietorContract)) {
            log.error("签署任务逾期事件，签署任务不存在，signTaskId:{}", signTaskId);
            return;
        }

        String signTaskStatus = map.get("signTaskStatus").toString();
        // expired：已逾期
        if ("expired".equals(signTaskStatus)) {
            if (ObjectUtil.isNotEmpty(lesseeContract)) {
                lesseeContract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_OVERDUE);
                lesseeContract.setUpdateTime(DateUtil.date());
                lesseeContractService.updateLesseeContract(lesseeContract);
            }
            if (ObjectUtil.isNotEmpty(proprietorContract)) {
                proprietorContract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_OVERDUE.getValue());
                proprietorContract.setUpdateTime(DateUtil.date());
                proprietorContractService.updateProprietorContract(proprietorContract);
            }
        }
    }

    /**
     * 签署任务撤销
     *
     * @param map
     */
    private void canceled(Map<String, Object> map) {
        String signTaskId = map.get("signTaskId").toString();
        LesseeContract lesseeContract = lesseeContractService.selectLesseeContractByFlowId(signTaskId);
        ProprietorContract proprietorContract = proprietorContractService.selectProprietorContractByFlowId(signTaskId);
        if (ObjectUtil.isEmpty(lesseeContract) && ObjectUtil.isEmpty(proprietorContract)) {
            log.error("签署任务撤销事件，signTaskId:{}", signTaskId);
            return;
        }
        String signTaskStatus = map.get("signTaskStatus").toString();
        if ("task_terminated".equals(signTaskStatus)) {
            Object terminationNote = map.get("terminationNote");
            if (ObjectUtil.isNotEmpty(lesseeContract)) {
                lesseeContract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_TERMINATED);
                if (ObjectUtil.isNotNull(terminationNote)) {
                    lesseeContract.setRemark(terminationNote.toString());
                }
                lesseeContractService.updateLesseeContract(lesseeContract);
            }
            if (ObjectUtil.isNotEmpty(proprietorContract)) {
                proprietorContract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_TERMINATION.getValue());
                if (ObjectUtil.isNotNull(terminationNote)) {
                    proprietorContract.setRemark(terminationNote.toString());
                }
                proprietorContractService.updateProprietorContract(proprietorContract);
            }
        }
    }

    /**
     * 拒签事件
     *
     * @param map
     */
    private void visaRejected(Map<String, Object> map) {

        String actorId = map.get("actorId").toString();
        if (StrUtil.equals("乙方", actorId)) {
            String signTaskId = map.get("signTaskId").toString();
            LesseeContract lesseeContract = lesseeContractService.selectLesseeContractByFlowId(signTaskId);
            ProprietorContract proprietorContract = proprietorContractService.selectProprietorContractByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(lesseeContract) && ObjectUtil.isEmpty(proprietorContract)) {
                log.error("参与方拒签事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }
            if (ObjectUtil.isNotEmpty(lesseeContract)) {
                lesseeContract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_TERMINATED);
                lesseeContract.setUpdateTime(DateUtils.getNowDate());
                lesseeContractService.updateLesseeContract(lesseeContract);
            }
            if (ObjectUtil.isNotEmpty(proprietorContract)) {
                proprietorContract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_TERMINATION.getValue());
                proprietorContract.setUpdateTime(DateUtils.getNowDate());
                proprietorContractService.updateProprietorContract(proprietorContract);
            }
        }
    }

    public void finished(Map<String, Object> map) {

        String signTaskStatus = map.get("signTaskStatus").toString();
        // sign_progress：签署中 (签署参与方进行签署)
        // sign_completed：签署已完成 (签署所有参与方均已签署完成)
        // task_finished：任务已完成 (签署任务已成功结束)
        if (StrUtil.equals("task_finished", signTaskStatus)) {

            String signTaskId = map.get("signTaskId").toString();
            LesseeContract lesseeContract = lesseeContractService.selectLesseeContractByFlowId(signTaskId);
            ProprietorContract proprietorContract = proprietorContractService.selectProprietorContractByFlowId(signTaskId);
            if (ObjectUtil.isEmpty(lesseeContract) && ObjectUtil.isEmpty(proprietorContract)) {
                log.error("签署任务参与方签署成功事件，签署任务不存在，signTaskId:{}", signTaskId);
                return;
            }

            if (ObjectUtil.isNotEmpty(lesseeContract)) {
                LesseeContract contract = new LesseeContract();
                contract.setLesseeContractId(lesseeContract.getLesseeContractId());
                contract.setLesseeContractStatus(ContractConstants.LESSEE_CONTRACT_STATUS_SIGN_OFF);
                contract.setUpdateTime(DateUtils.getNowDate());
                lesseeContractService.updateLesseeContract(contract);

                // 签署完成 更新关联账单
                houseBillService.updateBillEnableStates(lesseeContract.getLesseeContractId(), BillStateEnum.BILL_ENABLE_STATES_ON.getValue());
                houseBillService.houseBillActivationTask();
            }
            if (ObjectUtil.isNotEmpty(proprietorContract)) {
                ProprietorContract contract = new ProprietorContract();
                contract.setProprietorContractId(proprietorContract.getProprietorContractId());
                contract.setContractStatus(ProprietorContractEnum.CONTRACT_STATUS_FINISH.getValue());
                contract.setUpdateTime(DateUtils.getNowDate());
                proprietorContractService.updateProprietorContract(contract);
                houseService.updateHouseByDelFlag(proprietorContract.getHouseId());

                // 签署完成 更新关联账单
                propertiesBillService.insertProprietorBillByHouse(proprietorContract.getHouseId());

            }
        }
    }

    /**
     * 签署任务参与方签署成功事件
     *
     * @param map
     */
    private void signed(Map<String, Object> map) {

        //String signTaskStatus = map.get("signTaskStatus").toString();
        // sign_progress：签署中 (签署参与方进行签署)
        // sign_completed：签署已完成 (签署所有参与方均已签署完成)
        // task_finished：任务已完成 (签署任务已成功结束)
        String signTaskId = map.get("signTaskId").toString();
        LesseeContract lesseeContract = lesseeContractService.selectLesseeContractByFlowId(signTaskId);
        ProprietorContract proprietorContract = proprietorContractService.selectProprietorContractByFlowId(signTaskId);
        if (ObjectUtil.isEmpty(lesseeContract) && ObjectUtil.isEmpty(proprietorContract)) {
            log.error("签署任务参与方签署成功事件，签署任务不存在，signTaskId:{}", signTaskId);
            return;
        }
        //合同id
        String contractId = "";
        //签署类型:1.甲方;2.乙方
        String signType = "";
        //合同类型:1,业主合同;2.租客合同
        String contractType = "";
        //身份标识,甲方、乙方
        String actorId = map.get("actorId").toString();
        if (ObjectUtil.isNotEmpty(lesseeContract)) {
            LesseeContract contract = new LesseeContract();
            if (StrUtil.equals("乙方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_B;
                contract.setPartyBSignFlag(ContractConstants.HAVE_SIGNED_FLAG);
            } else if (StrUtil.equals("甲方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_A;
                contract.setPartyASignFlag(ContractConstants.HAVE_SIGNED_FLAG);
            }
            contract.setUpdateTime(DateUtils.getNowDate());
            contract.setLesseeContractId(lesseeContract.getLesseeContractId());
            lesseeContractService.updateLesseeContract(contract);
            contractId = lesseeContract.getLesseeContractId();
            contractType = TenantConstants.CONTRACT_TYPE_LESSEE;
        }

        if (ObjectUtil.isNotEmpty(proprietorContract)) {
            ProprietorContract contract = new ProprietorContract();
            if (StrUtil.equals("乙方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_B;
                contract.setPartyBSignFlag(ContractConstants.HAVE_SIGNED_FLAG);
            } else if (StrUtil.equals("甲方", actorId)) {
                signType = TenantConstants.SIGN_TYPE_PARTY_A;
                contract.setPartyASignFlag(ContractConstants.HAVE_SIGNED_FLAG);
            }
            contract.setUpdateTime(DateUtils.getNowDate());
            contract.setProprietorContractId(proprietorContract.getProprietorContractId());
            proprietorContractService.updateProprietorContract(contract);
            contractId = proprietorContract.getProprietorContractId();
            contractType = TenantConstants.CONTRACT_TYPE_PROPRIETOR;
        }

        ElectronicVisaSignProgress electronicVisaSignProgress = electronicVisaSignProgressService.selectSignProgressByName(
                contractId, signType, contractType);
        if (ObjectUtil.isNotEmpty(electronicVisaSignProgress)) {
            electronicVisaSignProgress.setId(null);
            electronicVisaSignProgress.setSignProgress(TenantConstants.SIGN_PROGRESS_HAVE_SIGNED);
            electronicVisaSignProgressService.insertElectronicVisaSignProgress(electronicVisaSignProgress);
        }
    }

    /**
     * 企业用户授权事件
     *
     * @param map
     */
    public void enterpriseAuth(Map<String, Object> map) {
        String authResult = map.get("authResult").toString();
        if ("success".equals(authResult)) {
            String clientCorpId = map.get("clientCorpId").toString();
            String openCorpId = map.get("openCorpId").toString();

            ElectronicVisa electronicVisa = electronicVisaService.selectElectronicVisaByVisaId(Long.parseLong(clientCorpId));
            if (ObjectUtil.isEmpty(electronicVisa)) {
                log.error("企业用户授权事件，签署任务不存在，clientCorpId:{}", clientCorpId);
                return;
            }
            electronicVisa.setOpenId(openCorpId);
            try {
                CorpIdentityInfoRes corpIdentityInfoRes = faDaDaService.corpGetIdentityInfo(openCorpId);
                CorpIdentInfo corpIdentInfo = corpIdentityInfoRes.getCorpIdentInfo();
                electronicVisa.setOrganizationName(corpIdentInfo.getCorpName());
                electronicVisa.setSocialCreditCode(corpIdentInfo.getCorpIdentNo());

                List<EmployeeInfo> corpMemberList = faDaDaService.getCorpMemberList(openCorpId);
                EmployeeInfo employeeInfo = corpMemberList.get(0);
                Long memberId = employeeInfo.getMemberId();
                electronicVisa.setProxyOperatorOpenid(memberId.toString());

                electronicVisaService.updateElectronicVisa(electronicVisa);

                if (StrUtil.isNotBlank(electronicVisa.getTenantId())) {
                    Tenant tenant = new Tenant();
                    tenant.setTenantId(electronicVisa.getTenantId());
                    tenant.setElectronicVisaStatus(TenantConstants.ELECTRONIC_VISA_STATUS_OPEN);
                    tenantService.updateTenant(tenant);
                }

                ProxyService proxyService = proxyServiceService.selectProxyServiceByConUserId(electronicVisa.getProprietorUserId());
                if (ObjectUtil.isEmpty(proxyService)) {
                    return;
                }
                //修改代理服电子签认证状态
                proxyServiceService.updateElectronicVisaStatusAuth(electronicVisa.getProprietorUserId());
                if (ProprietorConstants.MERCHANT_STATUS_ACCOUNT_OPENED_BOUND.equals(proxyService.getSplitMerchantStatus())) {
                    Proprietor proprietor =  new Proprietor();
                    proprietor.setProprietorId(proxyService.getProprietorId());
                    proprietor.setProxyServiceStatus(ProprietorConstants.PROXY_SERVICE_STATUS_FINISH);
                    proprietorService.updateProprietor(proprietor);
                }
            } catch (Exception e) {
                log.error("企业用户授权事件，获取企业信息失败:{}", e.getMessage(), e);
            }
        }
    }

    /**
     * 个人用户授权事件
     *
     * @param map
     */
    public void userAuth(Map<String, Object> map) {
        String authResult = map.get("authResult").toString();
        if ("success".equals(authResult)) {
            String clientUserId = map.get("clientUserId").toString();
            String openUserId = map.get("openUserId").toString();

            ElectronicVisa electronicVisa = electronicVisaService.selectElectronicVisaByVisaId(Long.parseLong(clientUserId));
            if (ObjectUtil.isEmpty(electronicVisa)) {
                log.error("个人用户授权事件，签署任务不存在，clientUserId:{}", clientUserId);
                return;
            }
            electronicVisa.setOpenId(openUserId);
            try {
                // 获取用户信息
                UserIdentityInfoRes userIdentityInfoRes = faDaDaService.userGetIdentityInfo(openUserId);
                UserIdentInfo userIdentInfo = userIdentityInfoRes.getUserIdentInfo();
                electronicVisa.setOrganizationName(userIdentInfo.getUserName());
                electronicVisa.setCardNumber(userIdentInfo.getIdentNo());

                electronicVisaService.updateElectronicVisa(electronicVisa);

                ProxyService proxyService = proxyServiceService.selectProxyServiceByConUserId(electronicVisa.getProprietorUserId());
                if (ObjectUtil.isEmpty(proxyService)) {
                    return;
                }
                //修改代理服电子签认证状态
                proxyServiceService.updateElectronicVisaStatusAuth(electronicVisa.getProprietorUserId());
                if (ProprietorConstants.MERCHANT_STATUS_ACCOUNT_OPENED_BOUND.equals(proxyService.getSplitMerchantStatus())) {
                    Proprietor proprietor =  new Proprietor();
                    proprietor.setProprietorId(proxyService.getProprietorId());
                    proprietor.setProxyServiceStatus(ProprietorConstants.PROXY_SERVICE_STATUS_FINISH);
                    proprietorService.updateProprietor(proprietor);
                }
            } catch (Exception e) {
                log.error("个人用户授权事件，获取个人信息失败:{}", e.getMessage(), e);
            }
        }
    }
}
